#include "string.h"

void memset(void * dst_, uint8_t value, uint32_t size)
{
	ASSERT(dst_ != NULL);
	uint8_t * dst = (uint8_t *)dst_;
	while(size-- > 0)
	{
		*dst++ = value;
	}
}

void memcpy(void * dst_, const void * src_, uint32_t size)
{
	ASSERT(dst_!=NULL && src_!= NULL);
	uint8_t * dst = dst_;
	const uint8_t * src = src_;
	while(size-- > 0) //Can size beyond the limit of string?It's not string.
	{
		*dst++ = *src++;
	}

}

int memcmp(const void* a_, const void* b_, uint32_t size)
{
	ASSERT(a_ != NULL || b_ != NULL);
	const char * a = a_;			//Referred to magnitude,can't use usigned data.
	const char * b = b_;
	while(size-- > 0)
	{
		/*if(*a > *b) return 1;
		else if(*a < *b) return -1;
		else
		{
			a++;
			b++;
		}*/
		//A more refinement implement.
		if(*a != *b)
			*a > *b?1:-1;
		a++;
		b++;
	}
	return 0;
}

char * strcpy(char * dst_, const char * src_)
{
	ASSERT(dst_ != NULL && src_ != NULL);//Why dst_ can't be NULL?
	char * r = dst_;
	while(*dst_++ = *src_++);
	return r;
}

uint32_t strlen(const char * str)
{
	ASSERT(str != NULL);
	uint32_t len = 0;
	while(*str++)
		len++;
	return len;
	//Or
	/*const char *p = str;
	while(*p++);
	return (p-str-1);*/
}

uint8_t strcmp(const char * a_, const char * b_)
{
	ASSERT(a_ != NULL || b_ != NULL);
	const char * a;
	const char * b;
	/*while(*a && *b)
	{
		if(*a != *b)
			*a > *b?1:-1;
		a++;
		b++;
	}
	if (*a == 0 && *b == 0) return 0;
	else if (*a != 0 && *b == 0) return 1;
	else return -1;*/
	while(*a != 0 && *a == *b)
	{
		a++;
		b++;
	}
	return (*a > *b)?1:-1;
}

char * strchr(const char * str, const uint8_t chr)
{
	ASSERT(str != NULL);
	while(*str != 0){
		if (*str == chr)
			return (char*)str;//(char*) specific.
		str++;
	}
	return NULL;
}

char * strrchr(const char * str, const uint8_t chr)
{
	ASSERT(str != NULL);
	/*const char * last = str;
	bool exist = false;
	while(*str)
	{
		if(*str == chr){
			last = str;
			exist = true;
		}
	}
	if(exist == true) return (char *)last;
	else return NULL; */
	const char * last_char = NULL;
	while(*str){
		if(*str++ == chr)
			last_char = str;
	}
	return (char *)last_char;
}

char * strcat(char * dst_, const char * src_)
{
	ASSERT(dst_ != NULL && src_ != NULL);
	char * str = dst_;
	while(*str++);
	str--;
	while(*str++ = *src_++);
	return dst_;
}

uint32_t strchrs(const char * str, const uint8_t chr)
{
	ASSERT(str != NULL);
	uint32_t times = 0;
	while(*str)
	{
		if(*str++ == chr)
			times++;
	}
	return times;
}


